package com.lovezy.platform.topic.service.impl;

import com.github.pagehelper.PageInfo;
import com.lovezy.platform.core.base.AppServer;
import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.base.enums.TrueOrFalseEnum;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.core.valid.ValidatorUtil;
import com.lovezy.platform.filestore.service.FileHelper;
import com.lovezy.platform.member.enums.MemberRoleEnum;
import com.lovezy.platform.member.model.Member;
import com.lovezy.platform.member.service.MemberService;
import com.lovezy.platform.topic.enums.TopicQueryType;
import com.lovezy.platform.topic.enums.TopicVideoSourceType;
import com.lovezy.platform.topic.form.TopicForm;
import com.lovezy.platform.topic.mapper.TopicMapper;
import com.lovezy.platform.topic.model.Topic;
import com.lovezy.platform.topic.query.TopicQuery;
import com.lovezy.platform.topic.service.TopicService;
import com.lovezy.platform.topic.video.TopicSourceHandler;
import com.lovezy.platform.topic.vo.TopicVo;
import com.lovezy.platform.wiki.form.FollowForm;
import com.lovezy.platform.wiki.model.Game;
import com.lovezy.platform.wiki.service.GameFollowService;
import com.lovezy.platform.wiki.service.GameService;
import com.lovezy.platform.wiki.vo.WikiVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

import static com.lovezy.platform.core.utils.ObjectUtil.copyTo;
import static com.lovezy.platform.member.exception.MemberExceptionEnum.MEMBER_ROLE_LIMIT;
import static com.lovezy.platform.topic.exception.TopicExceptionEnum.TOPIC_GAME_NOT_FOUND;
import static com.lovezy.platform.topic.exception.TopicExceptionEnum.TOPIC_NOT_FOUND;

/**
 * 文章话题服务实现
 * Created by jin on 2017/12/3.
 */
@Service
public class TopicServiceImpl extends MapperService<Topic, Integer, TopicMapper> implements TopicService{

    @Autowired
    private MemberService memberService;

    @Autowired
    private GameService gameService;

    @Autowired
    private GameFollowService gameFollowService;

    @Autowired
    private FileHelper fileHelper;

    @Autowired
    private AppServer appServer;

    @Override
    public Topic publishTopic(TopicForm form) {
        ValidatorUtil.validate(form, TopicForm.ADD);
        String mid = form.getMid();
        Member member = memberService.findByMemberId(mid);
        if (!Objects.equals(member.getRole(), MemberRoleEnum.ADMIN.value())) {
            throw new ServiceException(MEMBER_ROLE_LIMIT.getErrorCode(), MEMBER_ROLE_LIMIT.getErrorMsg());
        }

        Integer gameId = form.getGameId();
        if (gameId != null) {
            Game game = gameService.selectById(gameId);
            if (game == null) {
                throw new ServiceException(TOPIC_GAME_NOT_FOUND.getErrorCode(), TOPIC_GAME_NOT_FOUND.getErrorMsg());
            }
        }


        Date now = new Date();
        Topic topic = copyTo(form, new Topic());
        topic.setCreateId(mid);
        topic.setModifyId(mid);
        topic.setGmtCreate(now);
        topic.setGmtModify(now);
        topic.setStatus(StatusEnum.NORMAL.value());

        // 有视频
        if (form.getSourceType() == null) {
            if (form.getVideo() != null) {
                throw new ServiceException("视频信息为空");
            }
        } else {
            TopicSourceHandler handler = getHandler(form);
            topic.setCover(handler.getCover(topic.getCover()));
            topic.setVideo(handler.videoUrl(topic.getVideo()));
        }

        mapper.insert(topic);
        return topic;
    }

    private TopicSourceHandler getHandler(TopicForm form) {
        Byte topicType = form.getSourceType();
        TopicVideoSourceType topicVideoSourceType = TopicVideoSourceType.valueOf(topicType);
        return topicVideoSourceType.getHandlerInstance();
    }

    @Override
    public PageInfo<TopicVo> findTopicList(TopicQuery query) {
        if (query.getType() == null) {
            query.setType(TopicQueryType.NEW.value());
        }

        PageInfo<TopicVo> topics = Pager.doPageInfo(query, () -> mapper.findTopicList(query));
        topics.getList().forEach(t -> {
            convertWiki(t, query.getMid());
        });
        return topics;
    }

    @Override
    public Topic findById(Integer topicId) {
        Topic topic = mapper.selectByPrimaryKey(topicId);
        if (topic == null) {
            throw new ServiceException(TOPIC_NOT_FOUND.getErrorCode(), TOPIC_NOT_FOUND.getErrorMsg());
        }
        return topic;
    }

    @Override
    public TopicVo findTopicVoById(@NotNull Integer topicId) {
        TopicQuery query = new TopicQuery();
        query.setTopicId(topicId);
        TopicVo topicVo = mapper.findTopicById(query);
        convertWiki(topicVo, null);
        return topicVo;
    }

    private void convertWiki(TopicVo t,String mid) {
        WikiVo wiki = t.getWiki();
        if (wiki != null) {
            String logoUrl = fileHelper.toDownloadUrl(wiki.getLogo());
            wiki.setLogo(logoUrl);

            if (mid != null) {
                FollowForm followForm = new FollowForm();
                followForm.setMemberId(mid);
                followForm.setId(wiki.getId());
                boolean followed = gameFollowService.isFollowed(followForm);
                wiki.setHasFollow(followed ? TrueOrFalseEnum.TRUE.value() : TrueOrFalseEnum.FALSE.value());
            }
        }
        setViewUrl(t);
        String cover = t.getCover();
        if (cover != null) {
            t.setCover(fileHelper.toDownloadUrl(cover));
        }
    }

    private void setViewUrl(TopicVo topicVo) {
        String viewUrl = appServer.getViewDomain() + "view/topic/?topicId=" + topicVo.getTopicId();
        topicVo.setViewUrl(viewUrl);
    }

}
